const express = require('express')
const router = express.Router()
const BlogRoll = require('../model/blogRoll')

// 新增
router.post('/blogRoll/add', async (req, res) => {
  const { name, url} = req.body
  let nowTime = new Date()
  const data = await BlogRoll.create({
    name, url,
    createTime: nowTime,
  })
  if (data) {
    return res.send({
      code: 1,
      msg: '添加成功',
      data,
    })
  } else {
    return res.send({
      code: -1,
      msg: '添加失败',
      data,
    })
  }
})
// 修改
router.put('/blogRoll/edit', async (req, res) => {
  const {
    _id,
    name, url,
  } = req.body
  let nowTime = new Date()
  const data = await BlogRoll.updateOne({_id}, {
    name, url,
    updateTime: nowTime,
  })
  if(data.ok ===1){
    return res.send({
        code: 1,
        msg: '修改成功',
      })
  }else{
    return res.send({
        code: -1,
        msg: '修改失败',
      })
  }
  
})

// 查询列表带分页
router.get('/blogRoll/getList', (req, res) => {
  const { page, limit} = req.query
  BlogRoll.find({}, function (err, data) {
    if (err)
      return res.send({
        code: -1,
        msg: '请求失败',
      })
    let count = data.length
    BlogRoll.find({})
      .skip((page - 1) * parseInt(limit))
      .limit(parseInt(limit))
      .exec(function (err, data) {
        if (err)
          return res.send({
            code: -1,
            msg: '请求失败',
          })
        return res.send({
          code: 1,
          msg: '查询成功',
          total: count,
          data,
        })
      })
  })
})

// 根据id查询
router.get('/blogRoll/getId', async (req, res) => {
  const { id } = req.query
  const data = await BlogRoll.findById(id)
  if (data) {
    return res.send({
      code: 1,
      msg: '查询成功',
      data,
    })
  } else {
    return res.send({
      code: -1,
      msg: '查询失败',
      data,
    })
  }
})

// 根据id删除
router.delete('/blogRoll/del', async (req, res) => {
  const { id } = req.query
  const data = await BlogRoll.deleteOne({ _id: id })
  if (data.ok === 1) {
    return res.send({
      code: 1,
      msg: '删除成功',
    })
  } else {
    return res.send({
      code: -1,
      msg: '删除失败',
    })
  }
})

module.exports = router
